package client;

import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
import javax.naming.InitialContext;
import javax.swing.JOptionPane;
import org.jfree.ui.RefineryUtilities;
import Gui.ReturnsReport;
import Gui.LibrarianWindow;
import Control.UserDirector;
import Control.UserLibrarian;
import Control.UserSubscriber;
import Gui.ActivityReport;
import Gui.AddBook;
import Gui.Chartmake;
import Gui.DirectorWindow;
import Gui.EditDetails;
import Gui.FreezeSubscriber;
import Gui.Histogram;
import Gui.LendHistogram;
import Gui.LendReport;
import Gui.LendingCard;
import Gui.MainScreen;
import Gui.ReturnsReport;
import Gui.Rigester;
import Gui.Search;
import Gui.SubscriberWindow;
import Gui.UpdateBookDetails;
import Gui.Viewlending;
import Gui.Viewsubscriberdetail;
import Gui.Workers;
import Logic.LoginInfo;
import Logic.TaskAssignment;
import Gui.TheBookIsCopy;
import ocsf.client.AbstractClient;
import ocsf.server.ConnectionToClient;
/**
 * this class get answer from the server 
 * @author Ron Shenkerman
 * @author Gabi Revah
 * @author Aviad Almog
 * @author Ivan Onyshchenko
 */

public class ClientHendler extends AbstractClient {
	public static Object togui;

	
	  
	public ClientHendler(String host, int port) throws IOException {
		super(host, port);
		openConnection();
		
	}


	@SuppressWarnings("unchecked")
	protected void handleMessageFromServer(Object msg) {
		
		
		System.out.println("handleMessageFromServer:");
	
		if(msg instanceof UserSubscriber)
		{
			UserSubscriber user=(UserSubscriber)msg;
		    System.out.println("handleMessageFromServer: " + user.getUserName());
			user.OpenWindow();
			 

		}
		else if(msg instanceof UserLibrarian)
		{
			UserLibrarian user=(UserLibrarian)msg;
			System.out.println("handleMessageFromServer: " + user.getUserName());
			user.OpenWindow();
			
		}
		else if(msg instanceof UserDirector)
		{
			UserDirector user=(UserDirector)msg;
			System.out.println("handleMessageFromServer: " + user.getUserName());
			user.OpenWindow();
		}
		
		else if(msg.equals("LogoutCompleted"))
		{
			
			JOptionPane.showMessageDialog(null, "Logout finished");

		}
		
		else if(msg.equals("AddUser"))
		{
			
			JOptionPane.showMessageDialog(null, "User Added Successfully");

		}
		
		else if(msg.toString().contains("ViewSubscriberDetails"))
		{
			
		
				  String[] str;
				  msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
				  str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
				
				  Viewsubscriberdetail.viewDeatails(str);
				  
				 
		}
		else if(msg.toString().contains("LatesReport"))
		{
				ArrayList<Object> Arr=new ArrayList<Object>();
				Arr=(ArrayList<Object>) msg;
				Map<Double, Double> map = new HashMap<Double, Double>();
				
				Object o=Arr.get(3);
				map=(Map<Double, Double>) o;
				String[] str;
				Object o12=Arr.get(4);
				Double interval2=(Double)o12;
				final Chartmake c = new Chartmake("Lates Frequency Distribution Graph", map,interval2);
			 	RefineryUtilities.centerFrameOnScreen(c);
				c.setVisible(true);
				c.pack();
				msg= msg.toString().substring(1, msg.toString().length()-1); 
			 	str = msg.toString().split("[ , ] "); 
			 	
			 	 ReturnsReport.showmed(str);
				
					 
		}
		else if(msg.toString().contains("GetLatesBooks"))
		{
			  String[] str;
			  msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			  str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
			
			  ReturnsReport.fillcombobox(str);
				
					 
		}
		
		else if(msg.toString().contains("GetReportBy"))
		{
				ArrayList<Object> Arr=new ArrayList<Object>();
				Arr=(ArrayList<Object>) msg;
				Map<Double, Double> map = new HashMap<Double, Double>();
				
				Object o=Arr.get(3);
				map=(Map<Double, Double>) o;
				String[] str;
				Object o12=Arr.get(4);
				Double interval=(Double)o12;
				final Chartmake c = new Chartmake("Lates Frequency Distribution Graph", map,interval);
			 	RefineryUtilities.centerFrameOnScreen(c);
				c.setVisible(true);
				c.pack();
				msg= msg.toString().substring(1, msg.toString().length()-1); 
			 	str = msg.toString().split("[ , ] "); 
			 	ReturnsReport.showbybook(str);
				
					 
		}
		else if(msg.toString().contains("EditDetails"))
		{
			 String[] str;
			 msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
			
			  SubscriberWindow.ed.fillForm(str);
		
		}
		
		else if(msg.toString().contains("NewTelephone"))	
		{		
			
				JOptionPane.showMessageDialog(null, "Telephone successfully updated");
				EditDetails ed2 = new EditDetails(LoginInfo.UserName, null);
				MainScreen.card.add("EditDetails", ed2);
				MainScreen.cardLayot.show(MainScreen.card, "EditDetails");
		}
		
		else if(msg.toString().contains("NewEmail"))	
		{		
			
				JOptionPane.showMessageDialog(null, "Email successfully updated");
				EditDetails ed = new EditDetails(LoginInfo.UserName, null);
				MainScreen.card.add("EditDetails", ed);
				MainScreen.cardLayot.show(MainScreen.card, "EditDetails");
		}
		
		else if(msg.toString().contains("RemoveBook"))	
		{		
			
				String[] str;
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  

			 	

	//		  	LibrarianWindow.rb.updatewindow(str);

				JOptionPane.showMessageDialog(null, "Book Remove successfully");

			 	JOptionPane.showMessageDialog(null, "Book Remove successfully");

		}
		else if(msg.toString().contains("GetCategory"))	
		{		
			
				String[] str;
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
	
			 	LibrarianWindow.addbook = new AddBook(str);
			 	LibrarianWindow.addbook.initComponents();
				MainScreen.card.add("addbook", LibrarianWindow.addbook);
				MainScreen.cardLayot.show(MainScreen.card, "addbook");
				
		}
		else if(msg.toString().contains("AddBookDB"))
		{		
			JOptionPane.showMessageDialog(null, "The Book successfully Add to DB");
		}
		
		else if(msg.toString().contains("UpdatebookSearch"))	
		{		
			
				String[] str;
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[,] "); // remove the , from msg and spliting it to tiny str array parts  
			 	
			 
			 	LibrarianWindow.ubd.UpdateSearch(str);
			 	
			 
		}
		else if(msg.toString().contains("SearchLending"))	
		{		
				String[] str;
				msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
				str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  	
				Viewlending vi = new Viewlending(str);
				MainScreen.card.add("iewlending", vi);
				MainScreen.cardLayot.show(MainScreen.card, "iewlending");
		
						 	
		}

		else if(msg.toString().contains("Freeze"))	
		{		
			
				String[] str;
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
			  
			 	FreezeSubscriber.viewfreeze(str);
			 	
			 
		}
		
		else if(msg.toString().contains("LendingCard"))	
		{		
				String[] str;
				msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
				str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
				LendingCard ld = new LendingCard(str);
				
				
						 	
		}
		else if(msg.toString().contains("getlendreport"))	
		{		
				String[] str;
				msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
				str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  	
				LendReport lending = new LendReport(str);
				MainScreen.card.add("lendreportgui", lending);
				MainScreen.cardLayot.show(MainScreen.card, "lendreportgui");
		
						 	
		}
		
		else if(msg.equals("NotInTheSystem"))
		{		
			JOptionPane.showMessageDialog(null, "You are not logged into the system");
		}
		else if(msg.equals("MultipleConnection"))
		{		
			JOptionPane.showMessageDialog(null, " You alredy connected to the system! ");
		}
		
		else if(msg.toString().contains("NewTitle"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Title successfully updated");

		}
		else if(msg.toString().contains("NewAuthor"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Author successfully updated");

		}
		else if(msg.toString().contains("EditCategory"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Category successfully updated");

		}
		else if(msg.toString().contains("EditDescription"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Description successfully updated");

		}
		else if(msg.toString().contains("EditBuingDate"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Buying Date successfully updated");

		}
		else if(msg.toString().contains("EditCatalogNum"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Catalog number  successfully updated");

		}
		else if(msg.toString().contains("EditPrintDate"))	
		{		
			
			JOptionPane.showMessageDialog(null, "print Date successfully updated");

		}
		else if(msg.toString().contains("EditEditionNum"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Edition number successfully updated");

		}
		else if(msg.toString().contains("EditWanted"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Wanted successfully updated");

		}
		else if(msg.toString().contains("EditPlace"))	
		{		
			
			JOptionPane.showMessageDialog(null, "Place successfully updated");

		}
		else if(msg.toString().contains("UpdateBookDetailsFaild"))	
		{		
			
			JOptionPane.showMessageDialog(null, "The book id dosn't exsist in the DB");

		}
		
		
	
		else if(msg.toString().contains("GetBook"))	
		{		
			
				String[] str;
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
			  	LibrarianWindow.rb.updatewindow(str);
			 	
			 
		}
		else if(msg.toString().contains("Copylist"))	
		{		
			String[] str;
		 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
		 	str = msg.toString().split("[ , ] "); 

			  	TheBookIsCopy BookCopy =new TheBookIsCopy(str);
				BookCopy.setResizable(false);
				BookCopy.setSize(600, 400);
				BookCopy.setLocation(150, 150);
				BookCopy.setDefaultCloseOperation(BookCopy.EXIT_ON_CLOSE);
				BookCopy.setVisible(true);
			 
		}
		
		
		else if(msg instanceof String[])

		{
			 String[] str;
			 msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 str = msg.toString().split("[ , ] ");
			 if (str[0].contains("fail"))	
			{
				JOptionPane.showMessageDialog(null,str[1] + " Failed ","Failed",JOptionPane.WARNING_MESSAGE);
			}
			
			
		}
		else if(msg instanceof String )
		{
			
			if (msg.equals("CantRemove"))	
			{
				JOptionPane.showMessageDialog(null,"Book Can't Be Removed, The Book Is Allready Lended","Book Can't Be Removed, The Book Is Allredy Lended",JOptionPane.INFORMATION_MESSAGE);
			}	
				
			else if(msg.equals("BookIDDoesn'tExsists"))
			{
				JOptionPane.showMessageDialog(null,"Book ID Doesn't Exsists", "Message",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("frezzed"))
			{
				JOptionPane.showMessageDialog(null,"The Subscriber is freezed", "Message",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("Lock"))
			{
				JOptionPane.showMessageDialog(null,"The Subscriber is Locked", "Message",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("unfrezzed"))
			{
				JOptionPane.showMessageDialog(null,"The Subscriber is unfreezed", "Message",JOptionPane.INFORMATION_MESSAGE);
			}
			
			else if(msg.equals("booklendedcomplete"))
			{
				System.out.println("booklendedcomplete");
				JOptionPane.showMessageDialog(null,"book lended complete", "Lending",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("freezed"))
			{
				JOptionPane.showMessageDialog(null,"Subscriber freezed or Wrong Id", "Lending",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("bookalreadylended"))
			{
				System.out.println("bookalreadylended");
				JOptionPane.showMessageDialog(null,"book already lended", "Lending",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("ReturnDateExtended"))
			{
				JOptionPane.showMessageDialog(null,"Return Date Extended", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("CantExtendDateTooShort"))
			{
				JOptionPane.showMessageDialog(null,"Can't Extend Return Date Too Short", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("BookAllreadyReserved"))
			{
				JOptionPane.showMessageDialog(null,"Book Allready Reserved", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("Bookisnotlended"))
			{
				JOptionPane.showMessageDialog(null,"BookIs Not Lended", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("bookReturned"))
			{
				JOptionPane.showMessageDialog(null,"Book Returned", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("booknotReturned"))
			{
				JOptionPane.showMessageDialog(null,"Book Cant Be Returned He Is Not Lended", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("subscriberdoesntexists"))
			{
				JOptionPane.showMessageDialog(null,"Subscriber Id Doesn't Exists", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("MenualExtendcomplety"))
			{
				JOptionPane.showMessageDialog(null,"Menual Extend Complety", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("fail"))
			{
				JOptionPane.showMessageDialog(null,"The Application Faild to do this operation", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("booknotexsist"))
			{
				System.out.println("booknotexsist");
				JOptionPane.showMessageDialog(null,"Book Not Exsist", "Lending",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("Cantextendthebookiswanted"))
			{
				System.out.println("Cantextendthebookiswanted");
				JOptionPane.showMessageDialog(null,"Cant Extend The Book Is Wanted", "Lending",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("ExtendReturnDatecomplety"))
			{
				System.out.println("Cantextendthebookiswanted");
				JOptionPane.showMessageDialog(null,"Extend Return Date Complety", "Lending",JOptionPane.INFORMATION_MESSAGE);
			}
			else if(msg.equals("FailAddBook"))
			{
				System.out.println("FailAddBook");
				JOptionPane.showMessageDialog(null,"Book already exist");
			}
			
			
		}
		else if(msg.toString().contains("Search"))	
		{		
				
				String[] str;
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
			 	Search s= new Search();
			 	s.ShowResult(str);
			 	
			 	
		}
		else if(msg.toString().contains("XXsearch"))	
    {
  	  
  	  JOptionPane.showMessageDialog(null, "No search result");
  	  
  	  
    }


		
		else if(msg.toString().contains("Workers"))	
		{		
			
				String[] str;
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
			 	


			 	Workers work = new Workers(str); 	

		}
		
		else if(msg.toString().contains("activity"))	
		{		
			
				String[] str;
				
			 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
			 	str = msg.toString().split("[ , ] "); // remove the , from msg and spliting it to tiny str array parts  
			 	
			 	
			 	ActivityReport reportactivity = new ActivityReport(str);
			

		}
		else if(msg.toString().contains("OrderBook"))	
	    {
			String[] str;
		 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
		 	str = msg.toString().split("[ , ] "); 
	  	  if (str[1].equals("0"))
	  	  {
	  		  JOptionPane.showMessageDialog(null, "Can't make the order-You already have this book!");
	  	  }
	  	  else if (str[1].equals("1"))
	  	  {
	  		JOptionPane.showMessageDialog(null, "Your order has been successfully taken");
	  	  }
	  	  
	  	  
	    }
		else if(msg.toString().contains("Generate"))
		{
			String[] str;
		 	msg= msg.toString().substring(1, msg.toString().length()-1); // remove the [] from the msg by substring 
		 	str = msg.toString().split("[ , ] "); 
		 	
			ArrayList<Object> arr= new ArrayList<Object>();
			arr.add("ActivityReport");
			LibaryMain.chat.handleMessageFromGui(arr);
			
			int active = Integer.parseInt(str[1]);
			int lock = Integer.parseInt(str[2]);
			int freeze = Integer.parseInt(str[3]);
			int lend = Integer.parseInt(str[4]);
			int late = Integer.parseInt(str[5]);
			
			final Histogram histo =new Histogram("Activity Diagram",active,lock,freeze,lend,late);
			RefineryUtilities.centerFrameOnScreen(histo);
			histo.setVisible(true);
			histo.pack();
		    RefineryUtilities.centerFrameOnScreen(histo);
		    histo.setVisible(true);
			
			
			
			JOptionPane.showMessageDialog(null,"Activity Report Generated sucssefuly", "MESSAGE",JOptionPane.INFORMATION_MESSAGE);
		}
		else if(msg.toString().contains("showReport"))
		{
			@SuppressWarnings("unused")
			int i;
			ArrayList<Object> Arr=new ArrayList<Object>();
			Arr=(ArrayList<Object>) msg;
			Map<Double, Double> map = new HashMap<Double, Double>();
			Map<Double, Double> map1 = new HashMap<Double, Double>();
			Object o=Arr.get(5);
			map=(Map<Double, Double>)o;
			Object o12=Arr.get(6);
			Double interval=(Double)o12;
			String[] str;
			final Chartmake c = new Chartmake("Wanted Books",map,interval);
		 	RefineryUtilities.centerFrameOnScreen(c);
			c.setLocation(0, 0);
		 	c.setVisible(true);
			c.pack();
			Object o1=Arr.get(7);
			Object o13=Arr.get(8);
			map1=(Map<Double, Double>)o1;
			Double interval1=(Double)o13;
			final Chartmake c1 = new Chartmake("Not Wanted Books", map1,interval1);
		 	RefineryUtilities.centerFrameOnScreen(c);
		 	c.setLocation(500,0);
		 	c1.setVisible(true);
			c1.pack();
			
			msg= msg.toString().substring(1, msg.toString().length()-1); 
		 	str = msg.toString().split("[ , ] "); 
		 	
			int avgw = Integer.parseInt(str[1]);
			int midw = Integer.parseInt(str[2]);
			int avgn = Integer.parseInt(str[3]);
			int midn = Integer.parseInt(str[4]);
			
			
			final LendHistogram histo =new LendHistogram("Lend Diagram",avgw,midw,avgn,midn);
			RefineryUtilities.centerFrameOnScreen(histo);
			histo.setVisible(true);
			histo.pack();
		    RefineryUtilities.centerFrameOnScreen(histo);
		    histo.setVisible(true);
			
			
			
			
		}

	}
		
		

	  public void handleMessageFromGui(Object msg)
	  {
	    try
	    {
	    	sendToServer(msg);
	    }
	    catch(IOException e)
	    {
	 
	       System.out.println("Could not send message to server.  Terminating client.");
	      e.printStackTrace();
	      quit();
	    }
	  }
	  
	  /**
	   * This method terminates the client.
	   */
	  public void quit()
	  {
	    try
	    {
	      closeConnection();
	    }
	    catch(IOException e) {}
	    System.exit(0);
	  }
	}
	//End of ChatClient class

	
	
	
	